package com.lekang.system.config;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * 工作流部署配置
 * 自动部署BPMN流程定义
 * 
 * @author 刘卓
 * @date 2025-01-15
 */
@Slf4j
@Configuration
public class WorkflowDeploymentConfig implements CommandLineRunner {
    
    @Autowired
    private RepositoryService repositoryService;
    
    @Override
    public void run(String... args) throws Exception {
        log.info("==================== 开始自动部署工作流 ====================");
        
        try {
            // 使用资源加载器加载BPMN文件
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath:bpmn/*.bpmn20.xml");
            
            log.info("找到 {} 个BPMN流程定义文件", resources.length);
            
            for (Resource resource : resources) {
                String filename = resource.getFilename();
                log.info("正在部署流程: {}", filename);
                
                try {
                    // 部署流程
                    Deployment deployment = repositoryService.createDeployment()
                            .addInputStream(filename, resource.getInputStream())
                            .name(filename.replace(".bpmn20.xml", ""))
                            .deploy();
                    
                    log.info("✅ 流程部署成功: {} (部署ID: {})", filename, deployment.getId());
                    
                } catch (Exception e) {
                    log.error("❌ 流程部署失败: {} - {}", filename, e.getMessage(), e);
                }
            }
            
            // 输出已部署的流程定义
            log.info("==================== 当前已部署的流程定义 ====================");
            repositoryService.createProcessDefinitionQuery()
                    .orderByProcessDefinitionVersion().desc()
                    .list()
                    .forEach(pd -> {
                        log.info("流程定义: key={}, name={}, version={}, deploymentId={}", 
                                pd.getKey(), pd.getName(), pd.getVersion(), pd.getDeploymentId());
                    });
            
            log.info("==================== 工作流部署完成 ====================");
            
        } catch (Exception e) {
            log.error("工作流自动部署失败", e);
        }
    }
}
